<template>
  <div class="user-list-container">
    <!-- 查询表单 -->
    <!-- <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" label-width="80px">
        <el-row :gutter="20">
           <el-col :span="6">
            <el-form-item label="合作单位" prop="username">
              <companySelect />
            </el-form-item>
          </el-col> 
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.insuranceEffectiveStatus"
                placeholder="请选择状态"
                clearable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card> -->

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <div style="display: flex; margin-bottom: 20px">
        <el-button type="primary" @click="openAddDialog">创建</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="course_lesson_plans_id" label="ID" width="80" />
        <!-- <el-table-column prop="commercial_insurance_name" label="保险名称" /> -->
        <el-table-column prop="course_lesson_plans_title" label="标题" />
        <el-table-column prop="course_start_at" label="开始时间" />
        <el-table-column prop="course_end_at" label="结束时间" />

        <el-table-column prop="created_at" label="创建时间" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <!-- <el-button link @click="handleTableOption('edit', scope.row)"
              >编辑</el-button
            > -->
            <el-button link type="danger" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      v-if="dialogVisible"
      title="课时"
      width="1200"
      :before-close="handleCloseAddDialog"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="150px"
        class="demo-form"
      >
        <!-- 公司ID -->
        <el-form-item label="标题" prop="course_lesson_plans_title">
          <el-input v-model="form.course_lesson_plans_title" />
        </el-form-item>
        <el-form-item label="日期" prop="course_end_at">
          <el-date-picker
            v-model="date"
            type="date"
            value-format="YYYY-MM-DD"
            @change="timercChange"
          />
        </el-form-item>

        <el-form-item label="时间" prop="course_end_at">
          <el-select v-model="time" placeholder="请选择课程活动" filterable>
            <el-option
              v-for="item in timeSelectList"
              :key="item.time"
              :label="item.time"
              :value="item.time"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课件" prop="course_lesson_plans_path">
          <upload
            v-if="dialogVisible"
            type="file"
            :img-file="form.course_lesson_plans_path"
            :limit="1"
            @change="
              (val) => {
                console.log(val);
                this.form.course_lesson_plans_path = val;
              }
            "
          />
        </el-form-item>
        <el-form-item label="简介" prop="course_lesson_plans_info">
          <el-input
            v-model="form.course_lesson_plans_info"
            :autosize="{ minRows: 2 }"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="评分(1-5)" prop="course_lesson_plans_score">
          <el-input v-model="form.course_lesson_plans_score" type="number" />
        </el-form-item>

        <el-form-item prop="course_lesson_plans_score">
          <el-button @click="createrenwu">创建任务</el-button>
        </el-form-item>
        <el-form-item label="" prop="">
          <div v-for="(item, index) in renwuObj">
            任务{{ index + 1 }}
            <el-form-item label="任务标题" prop="">
              <el-input
                placeholder="请输入任务标题"
                v-model="item.course_task_title"
              ></el-input>
            </el-form-item>
            <el-form-item label="截止时间" prop="">
              <el-date-picker
                v-model="item.course_task_deadline_at"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                placeholder="请选择时间"
              />
            </el-form-item>
            <el-button @click="lianxitiCreate(index)">创建练习题</el-button>

            <el-form-item label="" prop="">
              <div v-for="(value, i) in item.timulist">
                题目{{ i + 1 }}:
                <el-form-item label="问题" prop="">
                  <el-input v-model="value.question_text"></el-input>
                  <el-form-item
                    :label="'选项' + (opi + 1)"
                    prop=""
                    v-for="(op, opi) in value.options_data"
                  >
                    <div style="display: flex">
                      <el-input v-model="op.option_text"></el-input>
                      是否为正确答案:
                      <el-switch
                        v-model="op.is_correct"
                        :active-value="1"
                        :inactive-value="0"
                        style="
                          --el-switch-on-color: #13ce66;
                          --el-switch-off-color: #ff4949;
                        "
                      />
                    </div>
                  </el-form-item>
                </el-form-item>
              </div>
            </el-form-item>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">
            {{ dialogType == "edit" ? "修改" : "创建" }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import tableMixin from "@/mixins/tableMixin";
import api from "@/request/api.js";
import upload from "@/components/upload.vue";

export default {
  name: "UserList",
  mixins: [tableMixin],
  components: { upload },
  props: {
    classId: {
      type: String,
      default: "",
    },
  },
  data() {
    // 结束日期验证
    const validateEndDate = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请选择结束日期"));
      }
      if (
        this.form.start_at &&
        new Date(value) < new Date(this.form.start_at)
      ) {
        return callback(new Error("结束日期不能早于开始日期"));
      }
      callback();
    };

    return {
      companyChildList: {},
      //查询参数
      queryParams: { course_id: this.classId },
      apimodel: "renwu",
      apival: "getList",
      // 状态选项
      statusOptions: [
        { value: -1, label: "全部" },
        { value: 1, label: "生效/上架" },
        { value: 2, label: "不生效/下架" },
        { value: 0, label: "预留" },
      ],
      //创建修改弹窗
      dialogVisible: false,
      dialogType: "",
      form: {
        course_lesson_plans_title: "",
        course_start_at: "",
        course_end_at: "",
        course_lesson_plans_score: "",
        course_lesson_plans_path: "",
        course_lesson_plans_info: "",
      },
      renwuObj: [],
      xitiObj: {},
      rules: {
        course_lesson_plans_title: [
          { required: true, message: "请输入标题", trigger: "change" },
        ],
        course_lesson_plans_score: [
          { required: true, message: "请输入评分", trigger: "change" },
        ],
        course_lesson_plans_path: [
          { required: true, message: "请输选择课件", trigger: "change" },
        ],
        course_lesson_plans_info: [
          { required: true, message: "请输入简介", trigger: "change" },
        ],
      },
      companys: [],
      date: "",
      time: "",
      timeSelectList: [
        {
          val: 1,
          time: "08:00-08:30",
        },
        {
          val: 2,
          time: "08:30-09:00",
        },
        {
          val: 3,
          time: "09:00-9:30",
        },
        {
          val: 4,
          time: "09:30-10:00",
        },
        {
          val: 5,
          time: "10:00-10:30",
        },
        {
          val: 6,
          time: "10:30-11:00",
        },
        {
          val: 7,
          time: "11:00-11:30",
        },
        {
          val: 8,
          time: "11:30-12:00",
        },
        {
          val: 9,
          time: "12:00-12:30",
        },
        {
          val: 10,
          time: "12:30-13:00",
        },
        {
          val: 11,
          time: "13:00-13:30",
        },
        {
          val: 12,
          time: "13:30-14:00",
        },
        {
          val: 13,
          time: "14:00-14:30",
        },
        {
          val: 14,
          time: "14:30-15:00",
        },
        {
          val: 15,
          time: "15:00-15:30",
        },
        {
          val: 16,
          time: "15:30-16:00",
        },
        {
          val: 17,
          time: "16:00-16:30",
        },
        {
          val: 18,
          time: "16:30-17:00",
        },
        {
          val: 19,
          time: "17:00-17:30",
        },
        {
          val: 20,
          time: "17:30-18:00",
        },
        {
          val: 21,
          time: "18:00-18:30",
        },
        {
          val: 22,
          time: "18:30-19:00",
        },
        {
          val: 23,
          time: "19:00-19:30",
        },
        {
          val: 24,
          time: "19:30-20:00",
        },
      ]
    };
  },
  mounted(){},
  methods: {
    lianxitiCreate(index) {
      this.renwuObj[index].timulist.push({
        question_text: "",
        is_active: "1",
        options_data: [
          {
            option_text: "",
            is_correct: 1,
            option_order: 1,
          },
          {
            option_text: "",
            is_correct: 0,
            option_order: 2,
          },
          {
            option_text: "",
            is_correct: 0,
            option_order: 3,
          },
          {
            option_text: "",
            is_correct: 0,
            option_order: 4,
          },
        ],
      });
    },
    createrenwu() {
      this.renwuObj.push({
        course_task_title: "",
        course_task_deadline_at: "",
        timulist: [],
      });
    },
    openAddDialog(option = "") {
      this.dialogVisible = true;
      this.dialogType = option;
    },

    // 加载公司数据

    handleCloseAddDialog() {
      this.dialogVisible = false;
      this.dialogType = "";
      this.form = {
        integral_goods_name: "",
        integral_goods_cover_path: "",
        integral_price: "",
        goods_sales: "",
      };
      this.resetForm();
    },
    // 编辑
    handleTableOption(option, row) {
      if (option == "edit") {
        this.form = row;
        this.openAddDialog(option);
      }
    },

    // 删除
    handleDelete(row) {
      this.$confirm("确认删除该积分商品吗?", "提示", {
        type: "warning",
      })
        .then(async () => {
          api.jifengood
            .del({
              integral_goods_id: row.integral_goods_id,
            })
            .then((res) => {
              if (res?.status == 200) {
                this.$message.success("删除成功");
                this.getTableData();
              }
            });
        })
        .catch(() => {});
    },
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          if (!this.date || !this.time) {
            this.$message.error("请检查表单填写");
            return;
          }
          this.form.course_start_at = this.date + " " + this.time.split("-")[0];
          this.form.course_end_at = this.date + " " + this.time.split("-")[1];
          if (this.renwuObj.length == 0) {
            this.$message.error("请创建任务");
            return;
          }
          for (let index = 0; index < this.renwuObj.length; index++) {
            const element = this.renwuObj[index];
            if (
              !element.course_task_deadline_at &&
              !element.course_task_title
            ) {
              this.$message.error("请检查表单填写");
              return;
            }
            if (element.timulist == 0) {
              this.$message.error("请创建题目");
              return;
            }
            for (let tm = 0; tm < element.timulist.length; tm++) {
              const elementtm = element.timulist[tm];
              if (!elementtm.question_text) {
                this.$message.error("请检查题目填写");
                return;
              }
            }
          }
          console.log(this.form, this.renwuObj);
          // 表单验证通过，提交逻辑
          console.log("表单提交:", this.form);
          api.jiaoan.create({course_id:this.classId ,...this.form }).then((res) => {
            if (res?.status == 200) {
                const _this = this
              for (let index = 0; index < _this.renwuObj.length; index++) {
                const element = _this.renwuObj[index];
                setTimeout(() => {
                  api.renwu
                    .create({
                      course_id: _this.classId,
                      course_lesson_plans_id:
                        res.data.content.data.course_lesson_plans_id,
                      course_task_deadline_at: element.course_task_deadline_at,
                      course_task_title: element.course_task_title,
                    })
                    .then((resrw) => {
                      if (resrw.data.code == 200) {
                   
                            api.xiti.create({
                              course_id: _this.classId,
                              course_lesson_plans_id:
                                res.data.content.data.course_lesson_plans_id,
                              course_task_id: resrw.data.content.data.course_task_id,
                              questions_data:element.timulist,
                            }).then(res=>{
                                if(res.data.code == 200){
                                    this.$message.success("操作成功")
                                    this.handleCloseAddDialog()
                                }
                            })
                        }
                    });
                }, 500);
              }
            }
          });

          // 这里可以添加API调用等提交逻辑
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.formRef.resetFields();
    },
    //选择地点
    handleRegionChange(val) {
      this.form.province_id = val.province;
      this.form.city_id = val.city;
      this.form.area_id = val.district;
    },
  },
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
